<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    :minHeight="100"
  >
    <BasicForm @register="registerForm">
      <template #handle_list>
        <FormItemRest>
          <template
            v-if="dataRef?.item?.meta?.handle_list && dataRef?.item?.meta?.handle_list?.length"
          >
            <draggable
              v-model="dataRef.item.meta.handle_list"
              :component-data="{
                type: 'transition-group',
              }"
              :animation="180"
              handle=".draggable-item"
            >
              <template #item="{ element, index }">
                <div class="flex gap-2 items-center mb-2">
                  <Checkbox v-model:checked="element.isUse" />
                  <TreeSelect
                    style="width: 200px"
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto', minWidth: '200px' }"
                    placeholder="请选择流程类型"
                    allow-clear
                    show-search
                    :tree-data="dirTreeList"
                    :fieldNames="{
                      label: 'name',
                      value: 'code',
                      children: 'children',
                    }"
                    treeNodeFilterProp="name"
                    v-model:value="element.code"
                    @change="(val, names) => getDirTreeChange({ val, names, element })"
                  />
                  <div
                    class="flex items-center w-240px"
                    v-if="dataRef?.item?.type == 'handle_list_summary'"
                  >
                    <Select
                      v-model:value="element.icon"
                      :options="imgList"
                      style="width: 200px"
                      placeholder="请选择图片"
                    />
                    <Image
                      :src="element.icon"
                      alt=""
                      style="width: 30px; margin-left: 5x"
                      v-if="element.icon"
                    />
                  </div>
                  <Select
                    v-model:value="element.type"
                    :options="handle_list_type"
                    style="width: 100px"
                    @change="handleModeChange($event, element)"
                    placeholder="请选择类型"
                  />
                  <Input
                    v-model:value="element.tabName"
                    style="width: 130px"
                    placeholder="流程名称"
                  />
                  <PlusOutlined @click="handleAdd" />
                  <CloseOutlined style="color: #f00" @click="handleDelete(index)" />
                  <DragOutlined class="cursor-pointer draggable-item" />
                </div>
              </template>
            </draggable>
          </template>
        </FormItemRest>
      </template>
      <template #flow_statistics>
        <FormItemRest>
          <template
            v-if="
              dataRef?.item?.meta?.flow_statistics && dataRef?.item?.meta?.flow_statistics?.length
            "
          >
            <draggable
              v-model="dataRef.item.meta.flow_statistics"
              :component-data="{
                type: 'transition-group',
              }"
              :animation="180"
              handle=".draggable-item"
            >
              <template #item="{ element, index }">
                <div class="flex gap-2 items-center mb-2">
                  <IconPicker v-model:value="element.icon" style="width: 180px" />
                  <TreeSelect
                    style="width: 120px"
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto', minWidth: '200px' }"
                    placeholder="请选择流程类型"
                    allow-clear
                    show-search
                    :tree-data="dirTreeList"
                    :fieldNames="{
                      label: 'name',
                      value: 'code',
                      children: 'children',
                    }"
                    treeNodeFilterProp="name"
                    v-model:value="element.code"
                    @change="(val, names) => getDirTreeChange({ val, names, element })"
                  />
                  <Input
                    v-model:value="element.title"
                    style="width: 120px"
                    placeholder="流程名称"
                    @change="handleTitleChange(element)"
                  />
                  <Checkbox v-model:checked="element.firstNameUse" style="width: 60px"
                    >启用</Checkbox
                  >
                  <Input
                    v-model:value="element.firstName"
                    style="width: 120px"
                    placeholder="名称"
                  />
                  <Input v-model:value="element.firstUnit" style="width: 50px" placeholder="单位" />
                  <Checkbox v-model:checked="element.secondNameUse" style="width: 60px"
                    >启用</Checkbox
                  >
                  <Input
                    v-model:value="element.secondName"
                    style="width: 120px"
                    placeholder="名称"
                  />
                  <Input
                    v-model:value="element.secondUnit"
                    style="width: 50px"
                    placeholder="单位"
                  />
                  <PlusOutlined @click="handleAdd_flow_statistics" />
                  <CloseOutlined style="color: #f00" @click="handleDelete_flow_statistics(index)" />
                  <DragOutlined class="cursor-pointer draggable-item" />
                </div>
              </template>
            </draggable>
          </template>
        </FormItemRest>
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, toRefs, reactive, onMounted, onUpdated } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { FormSchema } from '/@/components/Table';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    getChartTypes,
    getModulesAll,
    getFieldsByModuleCode,
    getBasicTree,
    getListCarouselPicture,
    getListAllCard,
  } from '/@/api/system/system';
  import { getDirTree, listDirByTypeCode } from '/@/api/process/process';
  import { deepMerge } from '/@/utils';
  import { isArray } from '/@/utils/is';
  import {
    handle_list_type,
    moduleList,
    imgList,
    firstName,
    secondName,
  } from './portalManageDesignModal.data';
  import { CloseOutlined, PlusOutlined, DragOutlined } from '@ant-design/icons-vue';
  import { Form, Select, Checkbox, Input, Image, TreeSelect } from 'ant-design-vue';
  import { IconPicker } from '/@/components/Icon';
  import draggable from 'vuedraggable';
  const FormItemRest = Form.ItemRest;

  export default defineComponent({
    components: {
      BasicModal,
      BasicForm,
      FormItemRest,
      Select,
      Checkbox,
      Input,
      IconPicker,
      Image,
      draggable,
      CloseOutlined,
      PlusOutlined,
      DragOutlined,
      TreeSelect,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      let isUpdate = ref(true);
      let dataRef = ref<Recordable>({});
      const imgeLists = ref([]);
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false, width: '70%' });
        isUpdate.value = !!data?.isUpdate;
        console.log('data', data);
        imgeLists.value = data?.imgeLists;
        dataRef.value = data?.record;
        let type = dataRef.value.item.type;

        if (
          type === 'chart_pie' ||
          type === 'chart_bar' ||
          type === 'chart_bar_c' ||
          type === 'chart_line' ||
          type === 'chart_gauge' ||
          type === 'chart_funnel' ||
          type === 'chart_radar'
        ) {
          await getChartTypesList(type);
        } else if (type === 'moduleLight') {
          await getFields(dataRef.value.item.meta.formCode);
        }

        setFieldsValue({
          ...dataRef.value.item,
        });
        updateSchema([
          {
            field: 'titleBackgroundImge',
            componentProps: {
              treeData: imgeLists.value,
            },
          },
          {
            field: 'boxBackgroundImge',
            componentProps: {
              treeData: imgeLists.value,
            },
          },
        ]);
        getDirTreeData();
        await fetchCarousePictureList();
      });

      const chartList = ref<Recordable>([]);
      const fieldList = ref<Recordable>([]);

      async function getChartTypesList(chartType) {
        await getChartTypes({
          chartType: chartType == 'chart_bar_c' ? 'chart_bar' : chartType,
        }).then((res) => {
          chartList.value = res || [];
          updateSchema([
            {
              field: 'meta.chartId',
              componentProps: {
                options: chartList.value,
              },
            },
          ]);
        });
      }

      async function getFields(moduleCode) {
        getFieldsByModuleCode({ moduleCode: moduleCode }).then((data) => {
          fieldList.value = data;
          // 需删除options，否则会因为返回的data数组里面每项存在options为{}致显示不了
          data.forEach((item) => {
            delete item['options'];
          });
          console.log('getFieldsByModuleCode fieldList.value', fieldList.value);
          updateSchema([
            {
              field: 'meta.leftField',
              componentProps: {
                showSearch: true,
                options: unref(fieldList),
              },
            },
          ]);
          updateSchema([
            {
              field: 'meta.rightField',
              componentProps: {
                showSearch: true,
                options: fieldList.value,
              },
            },
          ]);
        });
      }

      const carouselPictureList = ref<Recordable>([]);
      const fetchCarousePictureList = () => {
        getListCarouselPicture({}).then((res) => {
          carouselPictureList.value = res || [];
          updateSchema([
            {
              field: 'meta.carouselPictureId',
              componentProps: {
                options: carouselPictureList.value,
              },
            },
          ]);

          setFieldsValue({
            ...dataRef.value.item,
          });
        });
      };

      const dirTreeList = ref<Recordable[]>([]);
      //获取流程树
      const getDirTreeData = async () => {
        dirTreeList.value = (await getDirTree()) || [];
      };

      onMounted(() => {});

      onUpdated(() => {});

      const FormSchema: FormSchema[] = [
        {
          field: 'title',
          label: '标题',
          component: 'Input',
          required: true,
          colProps: {
            span: 8,
          },
        },
        {
          field: 'showTitle',
          label: '显示标题',
          component: 'Switch',
          required: true,
          defaultValue: true,
          componentProps: {
            checkedChildren: '是',
            unCheckedChildren: '否',
          },
          colProps: {
            span: 8,
          },
        },
        {
          field: 'titleAlign',
          label: '标题位置',
          component: 'RadioButtonGroup',
          required: true,
          defaultValue: 'left',
          componentProps: {
            options: [
              { label: '左', value: 'left' },
              { label: '中', value: 'center' },
              { label: '右', value: 'right' },
            ],
          },
          colProps: {
            span: 8,
          },
        },
        {
          field: 'titleSize',
          label: '标题大小',
          component: 'Select',
          required: true,
          defaultValue: '16',
          componentProps: {
            options: [
              { label: '12', value: '12' },
              { label: '14', value: '14' },
              { label: '16', value: '16' },
              { label: '18', value: '18' },
              { label: '22', value: '22' },
              { label: '26', value: '26' },
              { label: '28', value: '28' },
              { label: '30', value: '30' },
              { label: '32', value: '32' },
              { label: '34', value: '34' },
              { label: '36', value: '36' },
              { label: '38', value: '38' },
              { label: '48', value: '48' },
              { label: '60', value: '60' },
            ],
          },
          colProps: {
            span: 8,
          },
        },
        {
          field: 'titleColor',
          label: '标题颜色',
          component: 'ColorPicker',
          required: false,
          colProps: {
            span: 8,
          },
        },
        {
          field: 'cardHeadBorderBottomColor',
          label: '标题底线颜色',
          component: 'ColorPicker',
          required: false,
          colProps: {
            span: 8,
          },
        },
        {
          field: 'titleBackgroundColor',
          label: '标题背景颜色',
          component: 'ColorPicker',
          required: false,
          colProps: {
            span: 8,
          },
        },
        {
          field: 'titleBackgroundImge',
          label: '标题背景',
          component: 'TreeSelect',
          required: false,
          defaultValue: '',
          componentProps: {
            treeData: imgeLists.value,
            fieldNames: { label: 'title', value: 'value' },
            showSearch: true,
            treeNodeFilterProp: 'title',
            getPopupContainer: () => document.body,
            wrapFlex: true,
          },
          colProps: {
            span: 8,
          },
        },
        {
          field: 'boxBackgroundImge',
          label: '卡片背景',
          component: 'TreeSelect',
          required: false,
          defaultValue: '',
          componentProps: {
            treeData: imgeLists.value,
            fieldNames: { label: 'title', value: 'value' },
            showSearch: true,
            treeNodeFilterProp: 'title',
            getPopupContainer: () => document.body,
          },
          colProps: {
            span: 8,
          },
        },
        {
          field: 'boxBorder',
          label: '边框颜色',
          component: 'ColorPicker',
          required: true,
          componentProps: {
            style: 'width:200px',
            getPopupContainer: () => document.body,
          },
          colProps: {
            span: 8,
          },
        },
        {
          field: 'showHorn',
          label: '显示四角',
          component: 'RadioButtonGroup',
          required: true,
          defaultValue: '0',
          componentProps: {
            options: [
              { label: '否', value: '0' },
              { label: '是', value: '1' },
            ],
          },
          colProps: {
            span: 8,
          },
        },
        {
          field: 'hornColor',
          label: '四角颜色',
          component: 'ColorPicker',
          required: false,
          colProps: {
            span: 8,
          },
        },
        {
          field: 'imgeCenter',
          label: '图片居中',
          component: 'RadioButtonGroup',
          required: true,
          defaultValue: '0',
          componentProps: {
            options: [
              { label: '否', value: '0' },
              { label: '是', value: '1' },
            ],
          },
          colProps: {
            span: 8,
          },
        },
        {
          field: 'boxBackgroundColor',
          label: '背景色',
          component: 'ColorPicker',
          required: true,
          colProps: {
            span: 8,
          },
        },
        {
          field: 'rowCount',
          label: '条数',
          component: 'InputNumber',
          required: true,
          defaultValue: 6,
          colProps: {
            span: 8,
          },
          ifShow: ({ values }) => values.type !== 'Card',
        },
        {
          field: 'icon',
          label: '图标',
          component: 'IconPicker',
          // required: true,
          colProps: {
            span: 8,
          },
        },
        {
          field: 'type',
          label: '类型',
          component: 'Select',
          defaultValue: '',
          required: true,
          colProps: {
            span: 8,
          },
          componentProps: {
            showSearch: true,
            options: moduleList,
            optionFilterProp: 'label',
            getPopupContainer: () => document.body,
            onChange: (e) => {
              dataRef.value.item.meta.handle_list = [];
              if (
                e === 'chart_pie' ||
                e === 'chart_bar' ||
                e === 'chart_bar_c' ||
                e === 'chart_line' ||
                e === 'chart_gauge' ||
                e === 'chart_funnel' ||
                e === 'chart_radar'
              ) {
                getChartTypesList(e);
                setFieldsValue({ 'meta.chartId': '' });
              } else if (e === 'fileark') {
                // getBasicTree({code:fileark_dir})
              }
              if (e == 'handle_list' || e == 'handle_list_summary') {
                let obj = {
                  isUse: true,
                  code: '',
                  codeName: '',
                  tabName: '',
                  type: '',
                  typeName: '',
                };
                dataRef.value.item.meta.handle_list = [obj];
              } else if (e == 'flow_statistics') {
                // 输入框-公司发文 复用框 输入框-待办 复选框输入框-已办 选择icon 叉
                let obj = {
                  isUse: true,
                  code: '',
                  codeName: '',
                  firstUnit: '份',
                  firstNameUse: true,
                  firstName: firstName,
                  secondUnit: '份',
                  secondNameUse: true,
                  secondName: secondName,
                  icon: '',
                  title: '',
                };
                dataRef.value.item.meta.flow_statistics = [obj];
              } else if (e == 'flowLaunch') {
              } else if (e == 'fileark') {
                setFieldsValue({ 'meta.dirCode': [] });
              }
            },
          },
        },
        {
          field: 'meta.formCode',
          label: '模块',
          component: 'ApiSelect',
          required: true,
          colProps: {
            span: 8,
          },
          componentProps: {
            api: getModulesAll,
            labelField: 'name',
            valueField: 'code',
            showSearch: true,
            optionFilterProp: 'label',
            getPopupContainer: () => document.body,
            onChange: (e) => {
              setFieldsValue({ 'meta.leftField': '' });
              setFieldsValue({ 'meta.rightField': '' });
              getFields(e);
            },
          },
          ifShow: ({ values }) => values.type === 'module' || values.type === 'moduleLight',
        },
        {
          field: 'meta.flowTypeCode',
          label: '流程类型',
          component: 'ApiSelect',
          required: true,
          colProps: {
            span: 8,
          },
          componentProps: {
            api: listDirByTypeCode,
            params: { typeCode: 'root' },
            resultField: 'list',
            labelField: 'name',
            valueField: 'code',
            showSearch: true,
            optionFilterProp: 'name',
            getPopupContainer: () => document.body,
          },
          ifShow: ({ values }) => values.type === 'flowLaunch',
        },
        {
          field: 'meta.showSearch',
          label: '显示搜索区',
          component: 'RadioButtonGroup',
          // defaultValue: '0',
          componentProps: {
            options: [
              { label: '否', value: '0' },
              { label: '是', value: '1' },
            ],
          },
          colProps: { span: 8 },
          ifShow: ({ values }) => values.type === 'module',
        },
        {
          field: 'meta.pagination',
          label: '显示分页',
          component: 'RadioButtonGroup',
          // defaultValue: '0',
          componentProps: {
            options: [
              { label: '否', value: '0' },
              { label: '是', value: '1' },
            ],
          },
          colProps: { span: 8 },
          ifShow: ({ values }) =>
            values.type === 'module' ||
            values.type == 'handle_list' ||
            values.type == 'handle_list_summary',
        },
        {
          field: 'meta.showToolbar',
          label: '显示工具条按钮',
          component: 'RadioButtonGroup',
          // defaultValue: '0',
          componentProps: {
            options: [
              { label: '否', value: '0' },
              { label: '是', value: '1' },
            ],
          },
          colProps: { span: 8 },
          ifShow: ({ values }) => values.type === 'module',
        },
        {
          field: 'meta.showOpCol',
          label: '显示操作列',
          component: 'RadioButtonGroup',
          // defaultValue: '0',
          componentProps: {
            options: [
              { label: '否', value: '0' },
              { label: '是', value: '1' },
            ],
          },
          colProps: { span: 8 },
          ifShow: false, // ({ values }) => values.type === 'module',
        },
        {
          field: 'meta.cardId',
          label: '卡片',
          component: 'ApiSelect',
          required: true,
          colProps: {
            span: 8,
          },
          componentProps: {
            api: getListAllCard,
            labelField: 'name',
            valueField: 'id',
            showSearch: true,
            optionFilterProp: 'label',
            getPopupContainer: () => document.body,
          },
          ifShow: ({ values }) => values.type === 'Card',
        },
        {
          field: 'meta.leftField',
          label: '左侧字段',
          component: 'Select',
          defaultValue: '',
          required: true,
          colProps: {
            span: 8,
          },
          componentProps: {
            fieldNames: { label: 'title', value: 'name' },
            showSearch: true,
            options: fieldList.value,
            optionFilterProp: 'title',
            getPopupContainer: () => document.body,
          },
          ifShow: ({ values }) => values.type === 'moduleLight',
        },
        {
          field: 'meta.rightField',
          label: '右侧字段',
          component: 'Select',
          defaultValue: '',
          required: true,
          colProps: {
            span: 8,
          },
          componentProps: {
            fieldNames: { label: 'title', value: 'name' },
            showSearch: true,
            options: fieldList.value,
            optionFilterProp: 'title',
            getPopupContainer: () => document.body,
          },
          ifShow: ({ values }) => values.type === 'moduleLight',
        },
        {
          field: 'meta.dirCode',
          label: '目录',
          component: 'ApiTreeSelect',
          defaultValue: [],
          required: true,
          colProps: {
            span: 8,
          },
          componentProps: {
            api: getBasicTree,
            // showSearch: true,
            params: { code: 'fileark_dir' },
            multiple: true,
            maxTagCount: 3,
            resultField: 'list',
            fieldNames: {
              label: 'name',
              key: 'code',
              value: 'code',
            },
            treeNodeFilterProp: 'name',
            getPopupContainer: () => document.body,
          },
          ifShow: ({ values }) => values.type === 'fileark',
        },
        {
          field: 'meta.isShowDirImage',
          label: '显示栏目图片',
          component: 'RadioButtonGroup',
          defaultValue: '1',
          componentProps: {
            options: [
              { label: '否', value: '0' },
              { label: '是', value: '1' },
              { label: '轮播', value: '2' },
            ],
          },
          colProps: { lg: 24, md: 24 },
          ifShow: ({ values }) => values.type === 'fileark',
        },
        {
          field: 'meta.typeCode',
          label: '流程',
          component: 'ApiTreeSelect',
          defaultValue: '',
          required: false,
          colProps: {
            span: 8,
          },
          componentProps: {
            api: getDirTree,
            // showSearch: true,
            resultField: 'list',
            fieldNames: {
              label: 'name',
              key: 'code',
              value: 'code',
            },
            treeNodeFilterProp: 'name',
            getPopupContainer: () => document.body,
            // onChange: (val, names, trc) => {
            //   console.log('e,names,trc', { val, names, trc });
            //   setFieldsValue({ 'meta.typeCode': val });
            //   if (val) {
            //     const data = getFieldsValue();
            //     if (data.type == 'handle_list' || data.type == 'handle_list_summary') {
            //       let obj = {
            //         isUse: true,
            //         code: val,
            //         codeName: names[0],
            //         tabName: names[0],
            //         type: '',
            //         typeName: '',
            //       };
            //       console.log('data', data);
            //       if (data?.meta && isArray(dataRef.value.item.meta.handle_list)) {
            //         dataRef.value.item.meta.handle_list.push(obj);
            //       } else {
            //         dataRef.value.item.meta.handle_list = [obj];
            //       }
            //     }
            //     if (data.type == 'flow_statistics') {
            //       // 输入框-公司发文 复用框 输入框-待办 复选框输入框-已办 选择icon 叉
            //       let obj = {
            //         isUse: true,
            //         code: val,
            //         codeName: names[0],
            //         firstNameUse: true,
            //         firstName: firstName,
            //         secondNameUse: true,
            //         secondName: secondName,
            //         icon: '',
            //         title: names[0],
            //       };
            //       console.log('data', data);
            //       if (data?.meta && isArray(dataRef.value.item.meta.flow_statistics)) {
            //         dataRef.value.item.meta.flow_statistics.push(obj);
            //       } else {
            //         dataRef.value.item.meta.flow_statistics = [obj];
            //       }
            //     }
            //     console.log('dataRef.value', dataRef.value);
            //   }
            // },
          },
          ifShow: ({ values }) => values.type === 'flow',
        },
        {
          field: 'meta.chartId',
          label: '图形',
          component: 'Select',
          defaultValue: '',
          required: true,
          colProps: {
            span: 8,
          },
          componentProps: {
            // showSearch: true,
            fieldNames: {
              label: 'title',
              key: 'id',
              value: 'id',
            },
            options: chartList.value,
            treeNodeFilterProp: 'title',
            getPopupContainer: () => document.body,
          },
          ifShow: ({ values }) =>
            values.type === 'chart_pie' ||
            values.type === 'chart_bar' ||
            values.type === 'chart_bar_c' ||
            values.type === 'chart_line' ||
            values.type === 'chart_gauge' ||
            values.type === 'chart_funnel' ||
            values.type === 'chart_radar',
        },
        {
          field: 'meta.carouselPictureId',
          label: '图片轮播',
          component: 'Select',
          defaultValue: '',
          required: true,
          colProps: {
            span: 8,
          },
          componentProps: {
            // showSearch: true,
            fieldNames: {
              label: 'name',
              key: 'id',
              value: 'id',
            },
            treeNodeFilterProp: 'name',
            options: carouselPictureList.value,
            getPopupContainer: () => document.body,
          },
          ifShow: ({ values }) => values.type === 'CarouselPicture',
        },
        {
          field: 'meta.handleList', //handleListSummary
          label: '配置',
          component: 'Input',
          // required: true,
          colProps: {
            span: 24,
          },
          componentProps: {
            placeholder: '配置不能为空',
          },
          slot: 'handle_list',
          ifShow: ({ values }) =>
            values.type === 'handle_list' || values.type === 'handle_list_summary',
        },
        {
          field: 'meta.flowStatistics', //流程统计
          label: '配置',
          component: 'Input',
          // required: true,
          colProps: {
            span: 24,
          },
          componentProps: {
            placeholder: '配置不能为空',
          },
          slot: 'flow_statistics',
          ifShow: ({ values }) => values.type === 'flow_statistics',
        },

        // {
        //   field: 'carouselPictureId',
        //   label: '图片轮播',
        //   component: 'ApiSelect',
        //   required: true,
        //   colProps: {
        //     span: 8,
        //   },
        //   componentProps: {
        //     api: getListCarouselPicture,
        //     labelField: 'name',
        //     valueField: 'id',
        //     showSearch: true,
        //     optionFilterProp: 'label',
        //     getPopupContainer: () => document.body,
        //   },
        //   ifShow: ({ values }) => values.type === 'CarouselPicture',
        // },
      ];
      const [
        registerForm,
        { setFieldsValue, resetFields, validate, updateSchema, getFieldsValue },
      ] = useForm({
        labelWidth: 100,
        schemas: FormSchema,
        showActionButtonGroup: false,
        // labelCol: {
        //   span: 8,
        // },
        // wrapperCol: {
        //   span: 15,
        // },
        // actionColOptions: {
        //   span: 23,
        // },
      });

      const getTitle = '编辑';

      //配置类型
      const handleModeChange = (val, item) => {
        if (val) {
          item.typeName = handle_list_type.find((item) => item.value === val)?.label;
          if (item.tabName.indexOf(item.typeName) == -1) {
            item.tabName += item.typeName;
          }
        }
      };

      const handleAdd = () => {
        let obj = {
          isUse: true,
          code: '',
          codeName: '',
          tabName: '',
          type: '',
          typeName: '',
        };
        dataRef.value.item.meta.handle_list.push(obj);
      };

      //流程树变化
      const getDirTreeChange = ({ val, names, element }) => {
        const data = getFieldsValue();
        if (data.type == 'handle_list' || data.type == 'handle_list_summary') {
          element.codeName = '';
          element.tabName = '';
          if (val) {
            element.codeName = names[0];
            element.tabName = names[0];
            if (element.typeName) {
              element.tabName += element.typeName;
            }
          }
        } else if (data.type == 'flow_statistics') {
          element.codeName = '';
          element.title = '';
          if (val) {
            element.codeName = names[0];
            element.title = names[0];
            handleTitleChange(element);
            // if (element.title) {
            //   element.firstName = firstName + element.title;
            //   element.secondName = secondName + element.title;
            // }
          }
        }
      };

      //流程统计标题拼接
      const handleTitleChange = (element) => {
        element.firstName = firstName + element.title;
        element.secondName = secondName + element.title;
      };

      //删除
      const handleDelete = (index) => {
        dataRef.value.item.meta.handle_list.splice(index, 1);
      };

      //流程统计
      const handleAdd_flow_statistics = () => {
        let obj = {
          isUse: true,
          code: '',
          codeName: '',
          firstUnit: '份',
          firstNameUse: true,
          firstName: firstName,
          secondUnit: '份',
          secondNameUse: true,
          secondName: secondName,
          icon: '',
          title: '',
        };
        dataRef.value.item.meta.flow_statistics.push(obj);
      };

      //删除
      const handleDelete_flow_statistics = (index) => {
        dataRef.value.item.meta.flow_statistics.splice(index, 1);
      };

      async function handleSubmit() {
        try {
          let values = await validate();
          setModalProps({ confirmLoading: true });
          if (!values.embedded) {
            values.children = [];
          }
          deepMerge(dataRef.value.item, getFieldsValue());

          console.log('formData', dataRef.value);
          //办理列表 校验
          if (
            dataRef.value.item.type == 'handle_list' ||
            dataRef.value.item.type == 'handle_list_summary'
          ) {
            const handle_list = dataRef.value.item.meta.handle_list;
            if (!handle_list || handle_list?.length == 0) {
              createMessage.warning('配置信息不能为空');
              return;
            }
            if (handle_list.some((item) => !item.code || !item.tabName)) {
              createMessage.warning('配置信息不全');
              return;
            }
            const data = handle_list.map((item) => `${item.code}-${item.type}`);
            if (hasDuplicateData(data)) {
              createMessage.warning('配置信息不能重复');
              return;
            }
          }
          //流程统计 校验
          if (dataRef.value.item.type == 'flow_statistics') {
            const flow_statistics = dataRef.value.item.meta.flow_statistics;
            if (!flow_statistics || flow_statistics?.length == 0) {
              createMessage.warning('配置信息不能为空');
              return;
            }
            if (flow_statistics.some((item) => !item.code || !item.title)) {
              createMessage.warning('配置信息不全');
              return;
            }
            const data = flow_statistics.map((item) => `${item.code}`);
            if (hasDuplicateData(data)) {
              createMessage.warning('配置信息不能重复');
              return;
            }
          }
          closeModal();
          emit('success', dataRef.value);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }
      const hasDuplicateData = (arr) => {
        const obj = {};
        for (let i = 0; i < arr.length; i++) {
          if (obj[arr[i]]) {
            return true;
          }
          obj[arr[i]] = true;
        }
        return false;
      };
      return {
        registerModal,
        registerForm,
        getTitle,
        handleSubmit,
        handle_list_type,
        handleModeChange,
        handleDelete,
        handleAdd,
        dataRef,
        handleAdd_flow_statistics,
        handleDelete_flow_statistics,
        imgList,
        dirTreeList,
        getDirTree,
        getDirTreeChange,
        handleTitleChange,
      };
    },
  });
</script>
